package com.resou.reader.paycenter.p;

import android.arch.lifecycle.LifecycleOwner;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;

import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.MultiConfigBean;
import com.resou.reader.api.entry.PayResultBean;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.service.PayService;
import com.resou.reader.base.m.IModel;
import com.resou.reader.base.p.BasePresenter;
import com.resou.reader.commom.Constant;
import com.resou.reader.utils.log.DLog;
import com.resou.reader.paycenter.v.IBatchPayView;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.utils.ErrorUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ${Garrett} on 2018/10/24.
 * Contact me krouky@outlook.com
 */
public class BatchPayPresenter extends BasePresenter<IBatchPayView, IModel> {
    private static final String TAG = BatchPayPresenter.class.getSimpleName();
    private PayService mService;

    private String mBookId;
    private String mChapterId;

    public BatchPayPresenter(IBatchPayView view, String bookId, String chapterId) {
        this.view = view;
        mService = ApiImp.getInstance().getService(PayService.class);

        this.mBookId = bookId;
        this.mChapterId = chapterId;
    }

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        super.onCreate(owner);
        requestMultiConfig();
        view.getViewContext().registerReceiver(mReceiver, new IntentFilter(Constant.BC_BATCH_PAY));
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        view.getViewContext().unregisterReceiver(mReceiver);
        super.onDestroy(owner);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (view != null)
                view.initPayView();
        }
    };

    public void requestMultiConfig() {
        mService.multiConfigs(UserInstance.getToken(), mBookId, mChapterId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.<Result<List<MultiConfigBean>>>bindLifecycle())
                .subscribe(new Consumer<Result<List<MultiConfigBean>>>() {
                    @Override
                    public void accept(Result<List<MultiConfigBean>> listResult) {
                        int code = listResult.getCode();
                        DLog.i(TAG, "multiConfigs success, code == " + code);
                        List<MultiConfigBean> configBeans = listResult.getData();
                        List<MultiConfigBean> newList = new ArrayList<>();
                        if (configBeans != null && configBeans.size() > 0) {
                            for (int i = 0; i < configBeans.size(); i++) {
                                MultiConfigBean bean = configBeans.get(i);
                                if ("1".equals(bean.getIsEnabled())) {
                                    newList.add(bean);
                                }
                            }
                        }
                        view.onRequestConfigSuccessfully(newList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        DLog.e(TAG, "multiConfigs error! msg:" + throwable.getMessage());
                        throwable.printStackTrace();
                        view.onRequestConfigError();
                    }
                });
    }

    public void multiChapterPay(String bookName, String chapterName, int payCurrency, final int payType) {
        mService.multiChapterPay(UserInstance.getToken(), mBookId, bookName, mChapterId, chapterName, payCurrency, payType)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.<Result<PayResultBean>>bindLifecycle())
                .subscribe(new Consumer<Result<PayResultBean>>() {
                    @Override
                    public void accept(Result<PayResultBean> payResultBeanResult) {
                        int code = payResultBeanResult.getCode();
                        DLog.i(TAG, "multiChapterPay success, code == " + code);
                        if (code == 0) {
                            PayResultBean payResultBean = payResultBeanResult.getData();
                            UserInstance.getLoginData().setBlance(payResultBean.getCurrency());
                            UserInstance.getLoginData().setGiftBlance(payResultBean.getVoucher());
                            view.multiChapterPaySuccess(mChapterId, payType);
                            DLog.d("wuxuan", "Currency: " + (int) payResultBean.getCurrency() + " ,Voucher:" + (int) payResultBean.getVoucher());
                        } else {
                            ErrorUtils.showError("购买失败 code ==" + code);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        DLog.e(TAG, "multiChapterPay error! msg:" + throwable.getMessage());
                        ErrorUtils.showError(throwable);
                    }
                });
    }
}
